<?php

set_include_path(get_include_path() . ':' . dirname(__FILE__));
require_once('class.threesmug.php');
require_once('class.threelog.php');

$s = new ThreeSmug();
$l = ThreeLog::get();

if($s->testing) {
	$l->writeLine('Running in TESTING mode');
}

function pr($a) {
	print_r($a);
	echo "\n";
}

function get_local_structure($path) {
	$allowed_extensions = array(
		'jpg',
		'png',
		'gif',
		'jpeg',
		'tiff',
		'mov',
		'avi',
		'mkv',
		'mp4',
		'wmv',
		'flv',
		'm4a',
		'm4v'
	);

	// Strip the trailing slash if necessary
	$path = rtrim($path, "/\\");

	$structure = array();

	foreach (glob($path . '/*', GLOB_ONLYDIR) as $cat) {
		foreach (glob($cat . '/*', GLOB_ONLYDIR) as $album) {
			foreach (glob($album . '/*') as $file) {
				// Make sure file is less than 600 MB
				if(filesize($file) > 629145600) {
					continue;
				}

				$pi = pathinfo($file);
				if (in_array(strtolower($pi['extension']), $allowed_extensions)) {
					$structure[basename($cat)][basename($album)][] = $file;
				}
			}
		}
	}

	return $structure;
}

function prepare_file($path) {
	$iptc = get_iptc_data($path);

	$file = array();
	$file['path'] = $path;
	//$file['md5'] = md5_file($path);
	$file['filename'] = basename($path);
	$file['last_modified'] = date('Y-m-d h:i:s T', filemtime($path));

	if (!empty($iptc)) {
		if (!empty($iptc['2#120'][0])) {
			$file['caption'] = $iptc['2#120'][0];
		}

		if (!empty($iptc['2#025'])) {
			$file['keywords'] = implode(', ', $iptc['2#025']);
		}
	}

	return $file;
}

function get_iptc_data($image_path) {
	$size = getimagesize($image_path, $info);
	if (is_array($info)) {
		$iptc = iptcparse($info["APP13"]);
		return $iptc;
	}
}

function needUpdate($remote, $local) {
	global $s;

	$lTime = strtotime("{$local['last_modified']}");
	$rTime = strtotime("{$remote['LastUpdated']} PST");

	return $lTime > $rTime;
}

?>
